package com.appkudos.view;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.appkudos.controller.GroupController;
import com.appkudos.controller.UserController;
import com.appkudos.model.Category;
import com.appkudos.model.Group;
import com.appkudos.model.User;
import com.appkudos.view.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class UserConnectionsActivity extends Activity implements ViewBinder{
    ListView lv;
	private Activity PARENTACTIVITY; 
	User user;
	User friend;
	UserController uc;
    Button addFriendButton;
    Button joinGroupButton;
    Button createGroupButton;
	ArrayList<User> friends;
	ArrayList<Group> groups;
	Group group;
	
	// join group activity widgets
	ArrayList<Group> existing_groups;
    TextView search_text;
    TextView search_help_text;
    EditText search_box;
    Button findButton;
	GroupController gc;
	List<Group> matched_groups;
	
	// add friend activity widget
	List<User> existing_friends;
	TextView search_label;
	TextView search_term;
	
	// create group activity
	EditText groupname;
	Spinner category;
	EditText desc;
	Button createButton;
	List<Category> categories;
	
	String display_option;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        PARENTACTIVITY = this;
        
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        uc = new UserController();
        user = uc.getCurrentUser(extras);
        friend = uc.getFriend(extras);
        gc = new GroupController();
        
        // if friend is in fact the user, then make friend null
        if(friend != null && friend.getUsername().compareTo(user.getUsername())==0){
        	friend = null;
        }
        
        display_option = extras.getString(PARENTACTIVITY.getString(R.string.display_opt));

        if(display_option== null){
        	displayConnectionOptions();
        }else if(display_option.equals(this.getString(R.string.user_connection))){ // display select app
	     	   displayConnectionOptions();
	        }else if(display_option.equals(this.getString(R.string.user_friend))){ // display select app
	     	   displayFriendActivity();	       		
	        }else if(display_option.equals(this.getString(R.string.user_group))){ // display select app
	        	displayGroupActivity();		       		
	        }else if(display_option.equals(this.getString(R.string.add_friend))){ // display select app
	        	 displayAddFriendActivity();
	        }else if(display_option.equals(this.getString(R.string.join_group))){ // display select app
	        	 displayJoinGroupActivity();
	        }else if(display_option.equals(this.getString(R.string.create_group))){ // display select app
	        	 displayCreateGroupActivity();
	        }
       

   }
    
    // display option to go to friend or group list
    private void displayConnectionOptions(){
        // get list view from layout
    	setContentView(R.layout.view_only_list);
        lv=(ListView)findViewById(R.id.only_list);
        

        String lv_arr[]={"Friends","Groups"};
        ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, lv_arr);
        lv.setAdapter(adapter);        
        
		// when item is clicked go to either friend or group page
	    lv.setOnItemClickListener(new OnItemClickListener() {
	           public void onItemClick(AdapterView<?> parent, View view,
	               int position, long id) {	       
	        	   // if friend is selected
	        	   if(position == 0){// display friend activity
//	        		   displayFriendActivity();
	        		   Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
			           intent = uc.passCurrentUser(intent, user);
			           if(friend != null){
			        	   intent = uc.passFriend(intent, friend);
			           }
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.display_opt), PARENTACTIVITY.getString(R.string.user_friend));
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.tab), PARENTACTIVITY.getString(R.string.tab_user_connection));
	           		   startActivity(intent);
	        	   }else{// display group activity
//	        		   displayGroupActivity();
	        		   Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
			           intent = uc.passCurrentUser(intent, user);
			           if(friend != null){
			        	   intent = uc.passFriend(intent, friend);
			           }
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.display_opt), PARENTACTIVITY.getString(R.string.user_group));
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.tab), PARENTACTIVITY.getString(R.string.tab_user_connection));
	           		   startActivity(intent);
	        	   }
	             
	           }
	    });  
    }
    
    //helper method to display AddFriendActivity
    private void displayAddFriendActivity(){
    	setContentView(R.layout.view_add_friend);
    	
    	// get listview from layout
  	    lv=(ListView)findViewById(R.id.af_friend_list);
  	    search_box = (EditText) this.findViewById(R.id.af_friend_search);
  	    search_term = (TextView) this.findViewById(R.id.af_search_term);  
  	  search_label = (TextView) this.findViewById(R.id.af_search_label);
  	  
  	    // open a new page when add friend is clicked
  	    findButton = (Button) this.findViewById(R.id.af_find);
        findButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {    
       	      
             String keyword = search_box.getText().toString();
             search_box.setText("");
//       	      Toast.makeText(getApplicationContext(), "keyword is "+keyword,Toast.LENGTH_LONG).show();
       	      
       	      search_term.setText(keyword);
       	      search_label.setText("You looked up: ");
       	      // get existing friends of user
       	      existing_friends = uc.getFriendsOfUser(user.getUsername());
       	      
       	      if(keyword.compareTo("")==0){
       	    	  Toast.makeText(getApplicationContext(), "Please provide a name.",Toast.LENGTH_LONG).show();
       	      }else{
	       	      // get users that match the search keyword
	       	      List<User> matched_users = uc.searchForUser(keyword) ;
	           
	       		  // display list of matched users
	       		  if(matched_users.size() == 0)
	       			    Toast.makeText(getApplicationContext(), "No matched user.",Toast.LENGTH_LONG).show();
	       		  else{
	       			  	displayMatchedUsers(matched_users);
	//       				Toast.makeText(getApplicationContext(), "u:"+matched_users.get(0).getFirstname(),Toast.LENGTH_SHORT).show();
	       				lv.setVisibility(View.VISIBLE);
	       		  }
       		  }
            }
          });  		   
    }
    
    // helper method to display create gruop activity
    private void displayCreateGroupActivity(){
    	setContentView(R.layout.view_create_group);
    	groupname = (EditText) findViewById(R.id.cg_group_name);
    	category = (Spinner) findViewById(R.id.cg_category);
    	fillCategory();
    	desc = (EditText) findViewById(R.id.cg_desc_name);
    	createButton = (Button) findViewById(R.id.cg_b_create);
    	createButton.setOnClickListener(myListener);
    }
    
    private void fillCategory(){
    	categories = gc.getAllCategories();
    	
    	ArrayAdapter <CharSequence> adapter =
    		  new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item);
    	adapter.add("Choose any category");
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	for (int i=0; i<categories.size(); i++){
    		adapter.add(categories.get(i).getCatName());
    	}
    	
    	category.setAdapter(adapter); 
    	
    }
    
    private OnClickListener myListener = new OnClickListener() {
    	public void onClick(View v){
    		
    		String GroupName = groupname.getText().toString();
    		String GroupDesc = desc.getText().toString();
    		int Cat = category.getSelectedItemPosition();
    		//check if the info is complete
    		if (GroupName.equals("") ){
    			Toast.makeText(getApplicationContext(), "Please enter a group name.",Toast.LENGTH_LONG).show();
    		}else if(Cat == 0){
    			Toast.makeText(getApplicationContext(), "Please choose a category.",Toast.LENGTH_LONG).show();
    		}else if(GroupDesc.equals("")){
    			Toast.makeText(getApplicationContext(), "Please enter a description.",Toast.LENGTH_LONG).show();
    		}else{
    			gc.createGroup(GroupName,GroupDesc , categories.get(Cat-1).getCatid());
    			Group newgroup = gc.getGroupByName(GroupName);
    			uc.addUserToGroup(user.getUsername(),newgroup.getGroupID());
    			Toast.makeText(getApplicationContext(),"New group created: "+GroupName,Toast.LENGTH_LONG).show();
    			displayGroupActivity();
    		}
    	}
    };
    
    // helper method to display join group activity
    private void displayJoinGroupActivity(){
    	// set content view
    	setContentView(R.layout.view_search);
    	
    	// get all groups the user is in
	    existing_groups = (ArrayList<Group>) uc.getGroupsOfUser(user.getUsername());
        
	    // get and set widgets
        search_text = (TextView) this.findViewById(R.id.search_text);
        search_text.setText("Join Group");
        search_help_text = (TextView) this.findViewById(R.id.search_help_text);
	    search_box = (EditText) this.findViewById(R.id.search_box);
        search_help_text.setText("Enter keyword or category");
  	    search_term = (TextView) this.findViewById(R.id.s_search_term);  
    	search_label = (TextView) this.findViewById(R.id.s_search_label);

  	    // get listview from layout
  	    lv=(ListView)findViewById(R.id.search_result);
		//lv.setVisibility(View.GONE);
	      
  	    // open a new page when add friend is clicked
  	    findButton = (Button) this.findViewById(R.id.search_find_button);
        findButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {    
      	      String keyword = search_box.getText().toString();
      	      search_box.setText("");	      
      	      search_term.setText(keyword);
      	      search_label.setText("You looked up: ");
 	      
      	      // check to make sure user provides a keyword
      	      if(keyword.compareTo("")==0){
     	    	  Toast.makeText(getApplicationContext(), "Please provide a name.",Toast.LENGTH_LONG).show();
     	      }else{
	      	      matched_groups = gc.searchForGroup(keyword);
	      	      
	      	      
	      	      // display list of matched groups
	      	      if(matched_groups.size() == 0){ 
	      	    	  Toast.makeText(getApplicationContext(), "No matches",Toast.LENGTH_LONG).show();
	      	    	  lv.setVisibility(View.GONE);
	      	      }else{
	      	    	  displayMatchedGroupsBox(matched_groups);
	      	    	  lv.setVisibility(View.VISIBLE);
	      	    	  
	      	      }	
      	      }
      	      
            }
          });  	    
    }
    
    // helper method to display connection friend view
	private void displayFriendActivity(){
		setContentView(R.layout.view_friend_list);
		   
		   TextView title =(TextView)findViewById(R.id.vf_page_title);
		   addFriendButton = (Button) PARENTACTIVITY.findViewById(R.id.b_add_friend);
		   
		    // get listview from layout
		    lv=(ListView)findViewById(R.id.my_friend_list);
		    
		    // get name and friends for this user
		    if(friend == null){
		    	title.setText(user.getFirstname()+" "+user.getLastname()+"'s Friend List");
		    	friends = (ArrayList<User>) uc.getFriendsOfUser(user.getUsername());
		    	
		  	    // open a new page when add friend is clicked
		             addFriendButton.setOnClickListener(new OnClickListener() {
		             @Override
		             public void onClick(View v) {     
		                
		           		   
		           		 Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
				           intent = uc.passCurrentUser(intent, user);
		        		   intent.putExtra(PARENTACTIVITY.getString(R.string.display_opt), PARENTACTIVITY.getString(R.string.add_friend));
		        		   intent.putExtra(PARENTACTIVITY.getString(R.string.tab), PARENTACTIVITY.getString(R.string.tab_user_connection));
		           		   startActivity(intent);
		           		   
//		            	 displayAddFriendActivity();
		           		   
		             }
		           });  	    // open a new page when add friend is clicked
		    }else{
		    	title.setText(friend.getFirstname()+" "+friend.getLastname()+"'s Friend List");
		    	friends = (ArrayList<User>) uc.getFriendsOfUser(friend.getUsername());
		    	addFriendButton.setVisibility(View.GONE);
		    }
		    
		    // display friends
		    displayMatchedFriends(friends);
		  
			lv.setOnItemClickListener(new OnItemClickListener() {
			    public void onItemClick(AdapterView<?> parent, View view,
			        int position, long id) {
			      User friend = friends.get(position);
			      // When a user is clicked, go to the user's profile
	//		      Toast.makeText(getApplicationContext(), friend.getUsername()+" is clicked",Toast.LENGTH_SHORT).show();
			     
			      Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
			      intent = uc.passCurrentUser(intent, user);
			      intent = uc.passFriend(intent, friend);
			      startActivity(intent);
			    }
			});
	
	}

	// helper method to display connection group view
	private void displayGroupActivity(){
		 setContentView(R.layout.view_group_list);
		   
	  	    // get listview from layout
	  	    lv=(ListView)findViewById(R.id.my_group_list);
	  	   TextView title =(TextView)findViewById(R.id.vg_page_title);
	  	 joinGroupButton = (Button) PARENTACTIVITY.findViewById(R.id.b_join_group);
	  	createGroupButton = (Button) PARENTACTIVITY.findViewById(R.id.b_create_group);
	  	    // get the groups this user belongs
		    // get friends for this user
	  	    if(friend == null){
	  	    	title.setText(user.getFirstname()+" "+user.getLastname()+"'s Group List");
	  	    	groups = (ArrayList<Group>) uc.getGroupsOfUser(user.getUsername());
	  	   // open a new page when add friend is clicked
 	        joinGroupButton.setOnClickListener(new OnClickListener() {
 	        
 	        	@Override
 	             public void onClick(View v) {     
// 	        		displayJoinGroupActivity();
 	                Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
			           intent = uc.passCurrentUser(intent, user);
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.display_opt), PARENTACTIVITY.getString(R.string.join_group));
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.tab), PARENTACTIVITY.getString(R.string.tab_user_connection));
	           		   startActivity(intent);
 	             }
 	           });  	    // open a new page when add friend is clicked
 	  	   
 	         
 	         createGroupButton.setOnClickListener(new OnClickListener() {
 	             @Override
 	             public void onClick(View v) {  
// 	            	 displayCreateGroupActivity();
 	            	   Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
			           intent = uc.passCurrentUser(intent, user);
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.display_opt), PARENTACTIVITY.getString(R.string.create_group));
	        		   intent.putExtra(PARENTACTIVITY.getString(R.string.tab), PARENTACTIVITY.getString(R.string.tab_user_connection));
	           		   startActivity(intent);
 	             }
 	           }); 
	  	    	
	  	    }else{
	  	    	title.setText(friend.getFirstname()+" "+friend.getLastname()+"'s Group List");
	  	    	groups = (ArrayList<Group>) uc.getGroupsOfUser(friend.getUsername());
	  	    	joinGroupButton.setVisibility(View.GONE);
     	  	createGroupButton.setVisibility(View.GONE);
	  	    }
	  	   
	  	    // display friends
	  	    displayMatchedGroups(groups);
	  	  
			lv.setOnItemClickListener(new OnItemClickListener() {
			    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			      Group grp = groups.get(position);
			      // When a user is clicked, go to the user's profile
//			      Toast.makeText(getApplicationContext(), grp.getGroupName()+" is clicked",Toast.LENGTH_SHORT).show();
			     
			      Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
	  		      intent = uc.passCurrentUser(intent, user);
	              intent = uc.passCurrentGroup(intent, grp);
//	              intent = uc.passFriend(intent, friend);
	  		      startActivity(intent);
			    }
			});
	}
	
    // helper method to display matched users (only user)
	private void displayMatchedFriends(List list){
	  	Map<String, User> itemData;
	  	User matched;
	  	List<Map<String, User>> listData = new ArrayList<Map<String, User>>();
	  	
	  	// put the friends into a hashmap (used for input by simple adapter)
	  	for(int j=0; j<list.size();j++){
	  		itemData = new HashMap<String, User>(1);
	  		matched = (User) list.get(j);
	  		itemData.put("single_list_item", matched);
	  		listData.add(itemData);
	  	}    
	
	  	// bind simple adapter to the list view
	      SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.single_text_item,
	              new String[] {
	                  "single_list_item"
	              }, new int[] {
	                  R.id.single_list_item
	              });
	      
	      // bind viewBinder to adapter and set adapter to listview
	      simpleAdapter.setViewBinder(this);
	      lv.setAdapter(simpleAdapter);
	  }
	
	// helper method to display matched group (only group)
	private void displayMatchedGroups(List list){
	  	Map<String, Group> itemData;
	  	Group matched;
	  	List<Map<String, Group>> listData = new ArrayList<Map<String, Group>>();
	  	
	  	// put the friends into a hashmap (used for input by simple adapter)
	  	for(int j=0; j<list.size();j++){
	  		itemData = new HashMap<String, Group>(1);
	  		matched = (Group) list.get(j);
	  		itemData.put("single_list_item", matched);
	  		listData.add(itemData);
	  	}    
	
	  	// bind simple adapter to the list view
	      SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.single_text_item,
	              new String[] {
	                  "single_list_item"
	              }, new int[] {
	                  R.id.single_list_item
	              });
	      
	      // bind viewBinder to adapter and set adapter to listview
	      simpleAdapter.setViewBinder(this);
	      lv.setAdapter(simpleAdapter);
	  }

	// helper method to display matched groups (groups with checkboxes)
	 private void displayMatchedGroupsBox(List list){
	    	Map<String, Group> itemData;
	    	List<Map<String, Group>> listData = new ArrayList<Map<String, Group>>();
	    	
	    	// put the groups into a hashmap (used for input by simple adapter)
	    	for(int j=0; j<list.size();j++){
	    		itemData = new HashMap<String, Group>(1);
	    		group = (Group) list.get(j);
	    		itemData.put("add_button", group);
	    		listData.add(itemData);
	    	}    

	    	// bind simple adapter to the list view
	        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.two_column_item,
	                new String[] {
	                    "add_button"
	                }, new int[] {
	                    R.id.add_button
	                });
	        
	        // bind viewBinder to adapter and set adapter to listview
	        simpleAdapter.setViewBinder(this);
	        lv.setAdapter(simpleAdapter);
	    }
	        
	// helper method to display matched users 
	private void displayMatchedUsers(List list){
	  	Map<String, User> itemData;
	  	User matched;
	  	List<Map<String, User>> listData = new ArrayList<Map<String, User>>();
	  	
	  	// put the groups into a hashmap (used for input by simple adapter)
	  	for(int j=0; j<list.size();j++){
	  		itemData = new HashMap<String, User>(1);
	  		matched = (User) list.get(j);
	  		itemData.put("add_button", matched);
	  		listData.add(itemData);
	  	}    
	
	  	// bind simple adapter to the list view
	      SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.two_column_item,
	              new String[] {
	                  "add_button"
	              }, new int[] {
	                  R.id.add_button
	              });
	      
	      // bind viewBinder to adapter and set adapter to listview
	      simpleAdapter.setViewBinder(this);
	      lv.setAdapter(simpleAdapter);
	  }
	
	@Override
	// view binders for the lists
	public boolean setViewValue(View view, Object data, String stringRepresetation) {  
		     TextView tv = (TextView) view;
		     if(data instanceof Group && view instanceof CheckedTextView){
		    	// get data for the row
			    	Group group = (Group) data;
			        CheckedTextView ck = (CheckedTextView) view;
			        
			        // bind information to textView
			        ck.setText(group.getGroupName());
			        ck.setTag(group.getGroupID());
			        ck.setCompoundDrawablesWithIntrinsicBounds(R.drawable.groupicon, 0, 0, 0);
			        
			        if(checkExistingGroup(group)){
			        	ck.setChecked(true);
			        }else{
			        	ck.setChecked(false);
		          	}

		          	ck.setOnClickListener(new View.OnClickListener() {
		               public void onClick(View v)
		               {
		            	   CheckedTextView ckbox = (CheckedTextView) v;
		            	   String grp = ckbox.getText().toString();
		            	   String gid = (String) ckbox.getTag();
		            	   
			   	           if(!ckbox.isChecked()){
			   	        	   ckbox.toggle();
			   	        	   uc.addUserToGroup(user.getUsername(),gid);
				   	           Toast.makeText(getApplicationContext(), "Successfully joined "+grp+" group",Toast.LENGTH_LONG).show();
				   	        displayGroupActivity();
			   	           }else{
			   	        	   Toast.makeText(getApplicationContext(), "You are already a member of "+grp,Toast.LENGTH_LONG).show();
			   	           }
		               }
		           });
		     }else if(data instanceof User && view instanceof CheckedTextView){
			  	  // get data for the row
			  	  User matched = (User) data;
			      CheckedTextView ck = (CheckedTextView) view;
			      
			      // bind the matched user to textView
			      ck.setText(matched.getUsername());
//			      ck.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon3, 0, 0, 0);
			      
			      boolean isFriend = checkExistingFriend(matched);
			      // check if user is an existing friend or is the same person
			      if(isFriend){
			    	  ck.setChecked(true);
			      }else{
			    	  ck.setChecked(false);
			      }
			      
			      if(user.getUsername().compareTo(matched.getUsername()) == 0){
			    	  ck.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon4, 0, 0, 0);
	   	           }else if(isFriend){
	   	        	ck.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon3, 0, 0, 0); 
	 	           }else{
	 	        	  ck.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon2, 0, 0, 0);
	   	           }
			      
			      ck.setOnClickListener(new View.OnClickListener() {
			          public void onClick(View v)
			          {
			        	   CheckedTextView ckbox = (CheckedTextView) v;
			        	   String friend = ckbox.getText().toString();
			 	           
			        	   if(user.getUsername().compareTo(friend) == 0){
			        		   Toast.makeText(getApplicationContext(), "You cannot add yourself as friend",Toast.LENGTH_LONG).show();
//			        		   CustomizedToast(getApplicationContext(), "You cannot add yourself as friend",Toast.LENGTH_LONG);
			   	           }else if(!ckbox.isChecked()){
			 	        	   ckbox.toggle();
			 	        	   uc.addFriend(user.getUsername(),friend);
			 	        	  Toast.makeText(getApplicationContext(), "User "+ friend+" has been added",Toast.LENGTH_LONG).show();
//			 	        	   CustomizedToast(getApplicationContext(), ""+ friend+" has been added to your friends",Toast.LENGTH_LONG);
			 	        	  displayFriendActivity();
			 	           }else if(ckbox.isChecked()){
			 	        	  Toast.makeText(getApplicationContext(), "User "+friend+" is already your friend ",Toast.LENGTH_LONG).show();
//			 	        	   CustomizedToast(getApplicationContext(), "You are already a friend of "+friend,Toast.LENGTH_LONG);
			   	           }
			 	           	    
			          }
			      });

		     }else if(data instanceof User){ 
			 	 // get data for the row
			  	  User matched = (User) data;

			      // bind the matched user to textView
			      tv.setText(matched.getUsername());
			      tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon3, 0, 0, 0);
			      
		      }else if(data instanceof Group){
			  	  // get data for the row
			  	  Group matched = (Group) data;
			      
			      // bind the matched user to textView
			      tv.setText(matched.getGroupName());
			      tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.groupicon, 0, 0, 0);
			      
		      }

		      return true;
	  }
	
	 // check if the user is already friends with matched user
	  private boolean checkExistingGroup(Group matched){
		  boolean existed = false;
		  
		  for (int i=0; i<existing_groups.size();i++){
			  if(existing_groups.get(i).getGroupName().compareTo(matched.getGroupName()) == 0){
				  existed = true;
				  return existed;
			  }     
		  }
		  return existed;
	  }
	  
	  // check if the user is already friends with matched user
	  private boolean checkExistingFriend(User matched){
		  boolean existed = false;
		  if(matched.getUsername().compareTo(user.getUsername()) == 0){
			  existed = true;
			  return existed;
		  }
		  
		  for (int i=0; i<existing_friends.size();i++){
			  if(existing_friends.get(i).getUsername().compareTo(matched.getUsername()) == 0){
				  existed = true;
				  return existed;
			  }     
		  }
		  return existed;
	  }
	  
	  
	  public void CustomizedToast(Context context, String text, int duration){
		  LayoutInflater inflater = getLayoutInflater();
		  View layout = inflater.inflate(R.layout.toast,
		                                 (ViewGroup) findViewById(R.id.toast_layout_root));
		
		  ImageView image = (ImageView) layout.findViewById(R.id.toast_image);
		  image.setImageResource(R.drawable.ic_button_star);
		  TextView toast_text = (TextView) layout.findViewById(R.id.toast_text);
		  toast_text.setText(text);
		
		  Toast toast = new Toast(getApplicationContext());
		  toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		  toast.setDuration(Toast.LENGTH_LONG);
		  toast.setView(layout);
		  toast.show();
	  }
}